<template>
  <el-dialog
          :model-value="dialogVisible"
          title="媒资列表"
          :before-close="handleCancelDialog"
          width="80%"
          top="5vh"
  >
    <el-row class="mb10">
      <el-col :span="21">
        <el-select placeholder="请选择媒资类型"
                   v-model="queryList.mediatype"
                   clearable
                   size="mini"
                   class="input-w mr10"
                   @change="handleFilterMedia"
        >
          <el-option
                  v-for="mediatype in mediatypeList"
                  :key="mediatype.mediatype"
                  :value="mediatype.mediatype"
                  :label="mediatype.name"
          />
        </el-select>
        <el-select placeholder="请选择媒资分类"
                   v-model="queryList.catid"
                   clearable
                   size="mini"
                   class="input-w mr10"
                   @change="handleFilterMedia">
          <el-option
                  v-for="cat in catList"
                  :key="cat.catid"
                  :value="cat.catid"
                  :label="cat.name"
          />
        </el-select>
        <el-input
                placeholder="请输入媒资名称"
                v-model.trim="queryList.keyword"
                size="mini"
                clearable
                class="input-w mr10"
                @clear="handleFilterMedia"
                @keyup.enter="handleFilterMedia"
        />

        <el-button type="primary" size="mini" @click="handleFilterMedia">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
        <!--<el-button type="primary" size="mini">
          <el-icon>
            <search />
          </el-icon>
          高级搜索
        </el-button>-->
      </el-col>
      <el-col :span="3">
        <div align="right">
          <el-button type="primary" size="mini" @click="handleAddColumnMedia">
            <el-icon>
              <check />
            </el-icon>
            确定添加
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table
            ref="packageMediaTableRef"
            :data="tableData.listData"
            v-loading="isloading"
            border
            max-height="400px"
            @select="handleSelect"
            @select-all="handleSelectAll"
            @row-click="handleClickRow"
    >
      <el-table-column type="selection" width="55" :selectable="handleSelectAble" align="center" />
      <el-table-column label="预览" width="60">
        <template #default="{row}">
          <el-image
                  v-if="typeof row.thumbs == 'object' && row.thumbs.length > 0"
                  :src="row.thumbs[0].isself == 1 ? row.thumbs[0].viewurl + '&width=60px' : row.thumbs[0].viewurl"
                  :initial-index="initialIndex(row.thumbs)"
                  :preview-src-list="srcList"
          />
        </template>
      </el-table-column>
      <el-table-column label="媒资名称" prop="name" show-overflow-tooltip/>
      <el-table-column label="媒资类型" prop="mediatypename" />
      <el-table-column label="一级分类" prop="catname" />
      <el-table-column label="所属部门" width="100px" align="center" :show-overflow-tooltip="true">
        <template #default="{row}">
          <span v-if="corpid == row.corpid">{{row.groupname}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="来源企业" width="100px" align="center" :show-overflow-tooltip="true">
        <template #default="{row}">
          <span v-if="corpid != row.corpid && corpPartnerObj[row.corpid] != undefined">{{corpPartnerObj[row.corpid]}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px">
        <el-table-column label="更新时间" width="160px">
          <template #default="{row}">
            {{row.ctime.replace('T', ' ').replace('Z', '')}}<br />
            {{row.mtime.replace('T', ' ').replace('Z', '')}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="媒资状态">
        <template #default="{row}">
          <span v-if="row.inuse == 1">上线</span>
          <span v-else style="color: red">下线</span>
        </template>
      </el-table-column>
      <el-table-column label="添加状态">
        <template #default="{row}">
          <span v-if="row.columnids.includes(columnid)" style="color: red">已添加</span>
          <span v-else>未添加</span>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="mt10 mb15">
      <el-col :span="24">
        <table-pagination
                :queryList="queryList"
                :total="tableData.total"
                @pagination="getDataList"
        />
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
  import {reactive, ref, computed} from 'vue'
  import {useStore} from 'vuex'
  import {getPackageMedias, columnRelMedia} from "@/api/package/package";
  import { Search, Check } from "@element-plus/icons"
  import TablePagination from "@/views/public/TablePagination";
  import {ElMessage} from 'element-plus'
  import {getMediaTYpe} from "@/api/media/mediatype";
  import {getCategories} from "@/api/media/constant";
  import {getCorpPartner} from "@/api/corppartner";

  export default {
    name: "PackageMedia",
    components: {Search, TablePagination, Check},
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
      packageid: {
        type: Number,
        required: true
      },
      columnid: {
        type: Number
      }
    },
    emits: ['handleCancelDialog', 'reloadColumnMedias'],
    setup(props, context) {
      const store = useStore()
      const corpid = store.getters.corpinfo.corpid
      const isloading = ref(false)
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        packageid: props.packageid,
        keyword: undefined,
        mediatype: undefined,
        catid: undefined
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const srcList = ref([])
      const formData = reactive({
        columnid: undefined,
        packageid: undefined,
        mediaids: []
      })
      const packageMediaTableRef = ref(null)
      const mediatypeList = ref([])
      const catList = ref([])
      const corpPartnerObj = reactive({})

      const initialIndex = computed(() => {
        return (thumbs) => {
          const index = srcList.value.findIndex(d => d === thumbs[0].viewurl)
          return index
        }
      })

      /** 获取媒包媒资列表 **/
      const getDataList = () => {
        formData.columnid = props.columnid
        isloading.value = true
        resetSelectedMediaId()
        getPackageMedias(queryList).then(response => {
          isloading.value = false
          const {total, list} = response.data
          tableData.total = total
          tableData.listData = list
          srcList.value = []
          tableData.listData.forEach(row => {
            if (typeof row.thumbs == 'object' && row.thumbs.length > 0) {
              srcList.value.push(row.thumbs[0].viewurl)
            }
          })
        })
      }
      /** 媒资是否可选 **/
      const handleSelectAble = (row) => {
        return !row.columnids.includes(props.columnid)
      }
      /** 搜索媒资 **/
      const handleFilterMedia = () => {
        queryList.page = 1
        getCategoryList()
        getDataList()
      }
      /** 点击选择框 **/
      const handleSelect = (selection, row) => {
        getSelectedMediaId(row)
      }
      /** 全选 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (!formData.mediaids.includes(row.mediaid)) {
              formData.mediaids.push(row.mediaid)
            }
          })
        } else {
          resetSelectedMediaId()
        }
      }
      /** 点击行选择 **/
      const handleClickRow = (row) => {
        if (!row.columnids.includes(props.columnid)) {
          getSelectedMediaId(row)
        }
      }
      /** 获取选中的媒资ID **/
      const getSelectedMediaId = (row) => {
        if (formData.mediaids.includes(row.mediaid)) {
          const index = formData.mediaids.findIndex(d => d == row.mediaid)
          formData.mediaids.splice(index, 1)
          packageMediaTableRef.value.toggleRowSelection(row, false)
        } else {
          formData.mediaids.push(row.mediaid)
          packageMediaTableRef.value.toggleRowSelection(row, true)
        }
      }
      /** 重置选择的媒资 **/
      const resetSelectedMediaId = () => {
        formData.mediaids = []
      }

      /** 向栏目中添加媒资 **/
      const handleAddColumnMedia = () => {
        if (formData.mediaids.length <= 0) {
          ElMessage({type: 'warning', message: '请选择要添加的媒资', duration: 2000})
        } else {
          formData.packageid = props.packageid
          columnRelMedia(formData).then(response => {
            if (response.errcode == 0) {
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              handleCancelDialog()
              context.emit('reloadColumnMedias')
            }
          })
        }
      }

      /** 关闭弹框 **/
      const handleCancelDialog = () => {
        context.emit('handleCancelDialog')
      }

      /** 获取媒资分类列表 **/
      const getCategoryList = () => {
        getCategories({mediatype: queryList.mediatype, page: 1, pagesize: 1000}).then(response => {
          catList.value = response.data.list
        })
      }

      /** 获取媒资类型列表 **/
      const getMediatypeList = () => {
        getMediaTYpe().then(response => {
          mediatypeList.value = response.data
        })
      }

      /** 获取合作企业列表 **/
      const getCorpPartnerList = () => {
        getCorpPartner({partnertype: 0, corpid: corpid}).then(response => {
          if (response.errcode == 0) {
            response.data.list.forEach(function (v) {
              corpPartnerObj[v.corpid] = v.corpname
            })
          }
        })
      }

      const init = () => {
        // 获取合作企业列表
        getCorpPartnerList()
        queryList.page = 1
        queryList.pagesize = 25
        queryList.keyword = undefined
        queryList.packageid = props.packageid
        queryList.mediatype = undefined
        queryList.catid = undefined
        getMediatypeList()
        getDataList()
      }



      return {
        handleCancelDialog,
        isloading,
        tableData,
        queryList,
        init,
        srcList,
        initialIndex,
        getDataList,
        handleSelectAble,
        handleFilterMedia,
        handleSelect,
        handleSelectAll,
        handleClickRow,
        packageMediaTableRef,
        handleAddColumnMedia,
        mediatypeList,
        corpPartnerObj,
        corpid,
        catList
      }
    }
  }
</script>

<style scoped>

</style>
